package com.campsys.controller;

import com.campsys.common.Result;
import com.campsys.entity.User;
import com.campsys.service.dto.LoginDTO;
import com.campsys.service.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class LoginController {

    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginDTO loginDTO) {
        log.info("开始登录，用户名：{}", loginDTO.getUsername());
        try {
            Subject subject = SecurityUtils.getSubject();
            
            // 先退出之前的登录
            if (subject.isAuthenticated()) {
                subject.logout();
            }
            
            UsernamePasswordToken token = new UsernamePasswordToken(
                loginDTO.getUsername(),
                loginDTO.getPassword()
            );
            subject.login(token);
            
            User user = (User) subject.getPrincipal();
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            
            // 设置角色名称
            switch (user.getRoleType()) {
                case 0:
                    userVO.setRoleName("超级管理员");
                    break;
                case 1:
                    userVO.setRoleName("管理员");
                    break;
                case 2:
                    userVO.setRoleName("教师");
                    break;
                case 3:
                    userVO.setRoleName("学生");
                    break;
            }
            
            log.info("登录成功，返回用户信息：{}", userVO);
            return Result.ok(userVO);
            
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.ok();
    }
} 